﻿using System.Collections;
using System.Collections.Generic;
using System.Linq;
using JZ.JiangSu.Model.Entity;
using JZ.JiangSu.Model.Enum;
using System;
using System.Data;

namespace JZ.JiangSu.Repository
{
    //ibatis异步请求修改
    public class BaseRepository<T> : JZ.JiangSu.IRepository.IBaseRepository<T> where T : BaseEntity
    {
        protected readonly BatisRepository<T> repository = new BatisRepository<T>();//拿到MyBatis上下文
        private readonly string _className = typeof(T).Name;//拿到类名

        #region 基础基类方法，其他基类方法调用这几个完成实现
        public virtual int Add(T entity)
        {
            return entity == null ? 0 : repository.Insert(_className + "Add", entity);
        }

        public virtual int Delete(string whereCondition)
        {
            var ht = new Hashtable { { "whereCondition", whereCondition } };
            return repository.Delete(_className + "Delete", ht);
        }

        public virtual int AutoUpdate(Hashtable ht)
        {
            return ht != null ? repository.Update(string.Format("{0}Update", _className), ht) : 0;
        }


        public virtual int Update(T entity)
        {
            return entity == null ? 0 : repository.Update(_className + "Update", entity);
        }

        public virtual int Update(string fieldsSet, string whereCondition)
        {
            var ht = new Hashtable { { "fields", fieldsSet }, { "whereCondition", whereCondition } };
            return repository.Update(_className + "UpdateField", ht);
        }
        public virtual List<T> GetEntities(string whereCondition)
        {
            var ht = new Hashtable { { "whereCondition", whereCondition } };
            return repository.QueryForList(_className + "Select", ht).ToList();
        }

        public virtual IList<T> AutoGetEntity(Hashtable ht)
        {
            return repository.QueryForList(_className + "Auto", ht);
        }

        public virtual List<T> GetPagedEntities(int startRow, int endRow, Dictionary<string, SortEnum> sortConditionDic, string whereCondition, out int totalCount)
        {
            totalCount = GetTotalCount(whereCondition);
            if (totalCount > 0)
            {
                Hashtable ht = new Hashtable();
                ht.Add("startRow", startRow);
                ht.Add("endRow", endRow);
                List<string> strList = new List<string>();
                if (!(sortConditionDic == null || sortConditionDic.Count == 0))//有排序条件(PS:没排序条件默认按Id)
                {
                    foreach (KeyValuePair<string, SortEnum> item in sortConditionDic)
                    {
                        strList.Add(string.Format("{0} {1}", item.Key, item.Value == SortEnum.Desc ? "desc" : "asc"));
                    }
                    string sortCondition = string.Join(",", strList);
                    ht.Add("sortCondition", sortCondition);
                }
                if (!(string.IsNullOrEmpty(whereCondition) || string.IsNullOrWhiteSpace(whereCondition)))//where不为空
                {
                    ht.Add("whereCondition", whereCondition);
                }

                return repository.QueryForList(_className + "GetPagedEntities", ht).ToList();
            }
            return new List<T>();
        }
        public virtual int GetTotalCount(string whereCondition)
        {            
            if(!string.IsNullOrWhiteSpace(whereCondition))
            {
                Hashtable ht = new Hashtable();
                ht.Add("whereCondition", whereCondition);
                return repository.QueryForObject(_className + "GetTotalCount", ht);
            }
            return repository.QueryForObject(_className + "GetTotalCount");
        }

        //public virtual int GetNeedInfoTotals(Hashtable ht)
        //{
        //    return repository.QueryForObject(string.Format("Get{0}Totals", _className), ht);
        //}
        #endregion

        public int Delete(int id)
        {
            string whereCondition = string.Format(" id = {0} ", id);
            return Delete(whereCondition);
        }

        public int Delete(IList<int> idList)
        {
            string whereCondition = string.Format(" id in ( {0} )", string.Join(",", idList));
            return Delete(whereCondition);
        }
        public int Update(IList<int> entityIdList, Dictionary<string, object> modifyFields)
        {
            List<string> list = new List<string>();
            foreach (KeyValuePair<string, object> item in modifyFields)
            {
                list.Add(string.Format("{0} = '{1}'", item.Key, item.Value));
            }
            string whereCondition = " id in (" + string.Join(",", entityIdList) + ")";
            string fields = string.Join(",", list);
            return Update(fields, whereCondition);
        }

        public T GetEntityById(int entityId)
        {
            string whereCondition = string.Format(" id = {0} ", entityId);
            if (GetEntities(whereCondition).Count > 0)
            {
                return GetEntities(whereCondition).FirstOrDefault();
            }
            return null;
        }

        public T AutoGetEntityById(int entityId)
        {
            var ht = new Hashtable { { "Id", entityId } };
            return AutoGetEntity(ht).FirstOrDefault();
        }

        public List<T> GetEntitiesByIds(IList<int> entitiesIds)
        {
            if (entitiesIds.Count == 0)
            {
                return new List<T>();
            }
            string whereCondition = string.Format(" id in ( {0} )", string.Join(",", entitiesIds));
            return GetEntities(whereCondition);
        }

        public List<T> GetAllEntities()
        {
            return GetEntities(" 1=1");
        }
        /// <summary>
        /// 得到运行时ibatis.net动态生成的SQL
        /// </summary>
        /// <param name="statementName"></param>
        /// <param name="t"></param>
        /// <returns></returns>
        public Tuple<string, IDbDataParameter[]> GetSql(string statementName, T t)
        {
            return repository.GetRuntimeSql(statementName, t);
        }
    }
}